// pages/address/address.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    select: false,
    addressList: [],
    checkValue: ''
  },

  checkChangHandle(event) {
    this.setData({
      checkValue: event.detail
    })
  },

  checkAddresstHandle(event) {
    const {id} = event.currentTarget.dataset

    this.setData({
      checkValue: id
    })
  },

  // 编辑
  editHandle(event) {
    const {index} = event.currentTarget.dataset
    let data = this.data.addressList[index]

    wx.navigateTo({
      url: `/pages/address-edit/address-edit?address=${encodeURIComponent(JSON.stringify(data))}`,
    })
  },

  // 确认选择
  confirmSelectHandle() {
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];  //上一个页面
    let address = this.data.addressList.find(item => item.id == this.data.checkValue)

    if (address) {
      prevPage && prevPage.setData({
        address
      }, () => {
        wx.navigateBack({
          delta: 1,
        })
      })
    } else {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
    }
  },

  requestAddressList() {
    wx.ajax.post('queryReceiverAddressList.action').then(({result}) => {
      this.setData({
        addressList: result || []
      })
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let {select} = options
    let checkValue = select || ''
    
    if (select == 'true') {
      select = true
      checkValue = ''
    }

    select = !!select

    if (select) {
      wx.setNavigationBarTitle({
        title: '选择收货地址',
      })
    }

    this.setData({
      select,
      checkValue
    })

    wx.hideShareMenu()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.requestAddressList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})